package com.winit.openapi.ufile.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.query.Page;
import com.winit.common.spi.SPIException;
import com.winit.common.spi.command.GetByKeyCommand;
import com.winit.common.spi.context.CommandContext;
import com.winit.erp.spi.bpartner.vo.Bpartner;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.spi.ufile.FileTaskService;
import com.winit.spi.ufile.command.CreateFileTaskCommand;
import com.winit.spi.ufile.command.GetFileTaskCommand;
import com.winit.spi.ufile.command.QueryFileTaskCommand;
import com.winit.spi.ufile.command.RetryFileTaskCommand;
import com.winit.ufile.common.task.FileTask;
import com.winit.ums.spi.UmsUserService;
import com.winit.ums.spi.vo.user.UserVO;

@Controller
@RequestMapping(value = "/winit/ufile/task")
public class UFileTaskController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(UFileTaskController.class);

    @Resource
    private FileTaskService     fileTaskService;

    @Resource
    private UmsUserService      umsUserService;

    @RequestMapping(value = "/create")
    public String create(@ModelAttribute RequestMsg requestMsg) {

        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;

            CreateFileTaskCommand command = JSON.parseObject(json.toJSONString(), CreateFileTaskCommand.class);

            GetByKeyCommand<String> userCommand = new GetByKeyCommand<String>();
            userCommand.setCtx(CommandContext.getContext());
            userCommand.setSearchKey(requestMsg.getApp_key());
            UserVO userVo = null;

            try {
                userVo = umsUserService.queryByUsername(userCommand);
            } catch (SPIException e) {
                logger.info("不存在此账号的卖家，userName:" + requestMsg.getApp_key());
                throw new ApiException(ErrorCode.USER_NOT_FOUND);
            }

            Bpartner bpartner = CommandContext.getContext().get(ApiConstant.API_BPARTNER);
            command.setOwner(String.valueOf(userVo.getId()));
            command.setGroup(bpartner.getValue());

            fileTaskService.createFileTask(command);

        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        return SUCCESS;
    }

    @RequestMapping(value = "/retry")
    public String retry(@ModelAttribute RequestMsg requestMsg) {

        // 获取参数
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;

            RetryFileTaskCommand command = JSON.parseObject(json.toJSONString(), RetryFileTaskCommand.class);
            command.setCtx(CommandContext.getContext());
            fileTaskService.retryFileTask(command);

        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        return SUCCESS;
    }

    @RequestMapping(value = "/get")
    public String get(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;

            GetFileTaskCommand command = JSON.parseObject(json.toJSONString(), GetFileTaskCommand.class);
            command.setCtx(CommandContext.getContext());
            FileTask fileTask = fileTaskService.getFileTask(command);

            responseMsg.setData(fileTask);

        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        return SUCCESS;
    }

    @RequestMapping(value = "/queryList")
    public String queryTaskList(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;

            QueryFileTaskCommand command = JSON.parseObject(json.toJSONString(), QueryFileTaskCommand.class);
            command.setCtx(CommandContext.getContext());

            Bpartner bpartner = CommandContext.getContext().get(ApiConstant.API_BPARTNER);
            GetByKeyCommand<String> userCommand = new GetByKeyCommand<String>();
            userCommand.setSearchKey(requestMsg.getApp_key());
            UserVO userVo = null;

            try {
                userVo = umsUserService.queryByUsername(userCommand);
            } catch (SPIException e) {
                logger.info("不存在此账号的卖家，userName:" + requestMsg.getApp_key());
                throw new ApiException(ErrorCode.USER_NOT_FOUND);
            }

            command.setOwner(String.valueOf(userVo.getId()));
            command.setGroup(bpartner.getValue());

            Page<FileTask> fileTaskList = fileTaskService.queryFileTasks(command);

            if (fileTaskList != null && fileTaskList.content != null) {
                Map<String, Object> data = new HashMap<String, Object>();

                int pageNo = fileTaskList.getNumber() == 0 ? ApiConstant.PAGE_NO_DEFAULT : fileTaskList.getNumber();
                int pageSize = fileTaskList.getSize() == 0 ? ApiConstant.PAGE_SIZE_DEFAULT : fileTaskList.getSize();

                data.put("pageNo", pageNo);
                data.put("pageSize", pageSize);
                data.put("total", fileTaskList.total);
                data.put("taskList", fileTaskList.content);

                responseMsg.setData(data);
            }

        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        return SUCCESS;
    }

}
